package com.its.oa.system.permissionRole.service.impl;
import java.util.List;

import com.its.oa.model.Permission;
import com.its.oa.model.PermissionRole;
import com.its.oa.model.Role;
import com.its.oa.system.Role.dao.RoleDao;
import com.its.oa.system.permission.dao.PermissionDao;
import com.its.oa.system.permission.vo.PermissionVo;
import com.its.oa.system.permissionRole.dao.PermissionRoleDao;
import com.its.oa.system.permissionRole.service.PermissionRoleService;
import com.its.oa.util.EntityValidata;
import com.its.oa.util.StringUtil;


public class PermissionRoleServiceImpl implements PermissionRoleService {

	private PermissionRoleDao permissionRoleDao;
	private PermissionDao permissionDao;
	private RoleDao roleDao;

	public void setPermissionRoleDao(PermissionRoleDao permissionRoleDao) {
		this.permissionRoleDao = permissionRoleDao;
	}

	public void setPermissionDao(PermissionDao permissionDao) {
		this.permissionDao = permissionDao;
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	public String findOptionLevelsByRoleidPmsid(String roleids, String pmsid) {
		List<PermissionRole> prList = permissionRoleDao.findPmsRoleByRoleidPmsid(roleids, pmsid);
		String btnIds = "";
		if(EntityValidata.isNotEmpty(prList)){
			for (PermissionRole pr : prList) {
				btnIds += EntityValidata.isNotEmpty(btnIds)?","+pr.getBtnids():pr.getBtnids();				
			}
		}
		return StringUtil.removeSame(btnIds);
	}

	public List<PermissionVo> getAllPmsVoByRoleid(int roleid) {
		String pmsids = "";
		List<PermissionVo> chklist = permissionRoleDao.findCheckedPmsRoleVo(roleid);
		for (PermissionVo permissionVo : chklist) {
			pmsids+=EntityValidata.isNotEmpty(pmsids)?",'"+permissionVo.getPmsid()+"'":"'"+permissionVo.getPmsid()+"'";
			if(permissionVo.getRoleid()== roleid){
				permissionVo.setIsChecked("yes");
			}
		}
		List<PermissionVo> unchklist = permissionRoleDao.findUncheckedPmsRoleVo(pmsids);
		chklist.addAll(unchklist);
		return chklist;
	}

	public void addPermissionRole(int roleid, int pmsid, String btnCtrl) {
		PermissionRole pmsRole = new PermissionRole();
		Permission pms = permissionDao.findPermissionById(pmsid);
		Role role = roleDao.findById(roleid);
		if(role!=null && pms!=null){
			pmsRole.setBtnids(btnCtrl);
			pmsRole.setPermission(pms);
			pmsRole.setRole(role);
			permissionRoleDao.addPmsRole(pmsRole);
		}
	}

	public void delPermissionRole(int roleid, int pmsid) {
		PermissionRole pmsRole = permissionRoleDao.findPmsRoleByRoleidPmsid(roleid, pmsid);
		if(pmsRole!=null)
			permissionRoleDao.delPmsRole(pmsRole);
	}

	public void updatePermissionRole(int roleid, int pmsid, String btnCtrl) {
		PermissionRole pmsRole = permissionRoleDao.findPmsRoleByRoleidPmsid(roleid, pmsid);
		if(pmsRole!=null){
			pmsRole.setBtnids(btnCtrl);
			permissionRoleDao.updatePmsRole(pmsRole);
		}
	}

}
